package com.mydemo.common.pojo;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录用户
 * @author Last_Island
 * @version 1.0
 */
public class LoginUser implements UserDetails {
    private static final long serialVersionUID = 1L;
    private SysUser sysUser;
    private List<Role> roles;

    public LoginUser() {
    }

    public LoginUser(SysUser sysUser, List<Role> roles) {
        this.sysUser = sysUser;
        this.roles = roles;
    }

    public SysUser getSysUser() {
        return sysUser;
    }

    public void setSysUser(SysUser sysUser) {
        this.sysUser = sysUser;
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (roles != null) {
            List<Permission> permissions = new ArrayList<>();
            roles.forEach(role -> {
                        List<Permission> list = role.getPermissions();
                        if (list != null)
                            permissions.addAll(list);
                    }
            );
            return permissions.stream().distinct().collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getUsername();
    }

    /**
     * Indicates whether the user is enabled or disabled. A disabled user cannot be
     * authenticated.
     *
     * @return <code>true</code> if the user is enabled, <code>false</code> otherwise
     */
    @Override
    public boolean isEnabled() {
        return sysUser.getStatus().equals("0");
    }
}
